import React, { useState, useEffect } from 'react';


import { View, Text, Button as Button2, TextInput, TouchableOpacity, StyleSheet, PixelRatio, Alert, Image, Pressable, ImageBackground } from 'react-native';
import { styles } from '../MyStyle';
import { MyButton01, showToast } from '../UiComponents';

import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, reset } from './redux/actions';
import NativeLocalStorage from '../specs/NativeLocalStorage';

import { BackButton } from '../UiComponents';

import {
  createStaticNavigation,
  useNavigation,
} from '@react-navigation/native';
// import { Center } from 'native-base';

import { Center, Square, Circle } from 'native-base';

import { Loading } from '../Loading';
import { Flex } from '@ant-design/react-native';
import { Person } from './myclasses';

import axios from 'axios';

// https://redux.js.org/introduction/getting-started
// npm install redux react-redux


// 定义接口类型
interface UserData {
  // 根据实际返回的数据结构定义
  accessToken: string;
  companyId: string;
  companyName: string;
  qrCode: string;
  userId: string;
}

interface ApiResponse<T> {
  data: T;
  code: number;
  message: string;
}


// 登录请求函数
const login2 = async (sn: string): Promise<ApiResponse<UserData>> => {
  try {
    const response = await axios.post<ApiResponse<UserData>>(
      'https://applet.xmlights.com/robot/login',  // 修改为实际的 API 地址
      null, // POST 请求体，可能是空的
      {
        params: { sn },  // 查询参数
      }
    );
    return response.data;  // 返回数据
  } catch (error) {
    console.error('Login failed:', error);
    throw error;  // 或者返回错误消息
  }
};


export function Login() {
  const [base64Image, setBase64Image] = useState<string | null>('');


  const handleBackPress = (text: string) => {
    // 调用函数
    const sn = '12674E5';
    login2(sn)
      .then(response => {
        console.log('Login successful:', response);
        if (response.code === 200 && response.data.userId === null) {
          // showToast("登录失败：" + response.data.accessToken);
          // setBase64Image('');
          setBase64Image("data:image/png;base64,"+response.data.qrCode);
        }
        else
          if (response.code === 200 && response.data.userId !== null) {
            showToast("登录成功：" + response.data.accessToken);
          }
      })
      .catch(error => {
        console.error('Error:', error);
      });
  }
  

  return (<Flex justify="center"  direction='column' align="center" style={{backgroundColor: 'gold' }}>
  <MyButton01 text='LOGIN' onPress={handleBackPress}></MyButton01>
  <View style={{height:12}}></View>


<Image
        source={{uri:base64Image}} // Base64 数据作为图片的 URI
        style={styles2.qrCode}         // 设置图片尺寸
      />
<BackButton/>
</Flex>);
}

const styles2 = StyleSheet.create({
  qrCode: {
    width: 200,
    height: 200, // 固定尺寸为 200×200
    resizeMode: 'contain', // 确保图片完整显示
  },
});


